<?php

namespace Frieza\Modules\Search\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\AdmSearchKeyword\PresetSearchKeyword as mPresetSearchKeyword;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\service\position\AdmOperationModule;
use Doraemon\model\Position\PositionRules;


class PresetKeywordController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    private function _filterWhere($params)
    {
        if (isset($params['_columns_'])) {
            unset($params['_columns_']);
        }
        if (isset($params['_pjax'])) {
            unset($params['_pjax']);
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);
        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
            }
        }
        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }

    public function index(Request $request, Content $content, $type = 1)
    {
        $request = $request->all();
        $request = self::_filterWhere($request);
        $tab = new Tab();
        $tab->addLink(mPresetSearchKeyword::TYPE[mPresetSearchKeyword::TYPE_INDEX], '/admin/search/preset/recommend/' . mPresetSearchKeyword::TYPE_INDEX, $type == mPresetSearchKeyword::TYPE_INDEX);
        $limitArr = $request['LIMIT'];
        $list = mPresetSearchKeyword::selectByWhere(['LIMIT' => $limitArr, 'preset_type' => $type, 'preset_status' => mPresetSearchKeyword::STATUS_NORMAL]);
        $count = mPresetSearchKeyword::selectCount(['preset_type' => $type, 'preset_status' => mPresetSearchKeyword::STATUS_NORMAL]);
        $count = $count ? $count : 0;

        $taskRules = AdmOperationModule::getPositionRulesById(array_column($list, 'id'), PositionRules::MODULE_TYPE_SEARCH_KEYWORD);
        foreach ($list as &$row) {
            $row['user_profile'] = $taskRules[$row['id']] ?? [];
        }

        $gridModel = new pGridDataModel($list, $count, [
            'perPage' => $request['per_page'] ?: $request['LIMIT'][1]
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();
            $grid->column('id');
            $grid->column('keyword', '推荐词')->width(150);
            $grid->column('addtime', '添加时间');
            $grid->column('edittime', '修改时间');
            $grid->column('user_profile', '分群信息')->userProfile();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
            });
        });

        $list = $listGrid->render();
        return $content
            ->header('搜索预置词推荐管理')
            ->breadcrumb(
                ['text' => '搜索预置词推荐管理', 'url' => '/search/preset/recommend/' . $type]
            )
            ->body($tab)->row($list);
    }


    public function edit(Request $request, Content $content, $type = 1)
    {
        $request = $request->all();
        $header = '搜索预置词推荐管理';
        $info['preset_type'] = $type;
        $info['user_profile'] = [];
        $form = new Form($info);
        $form->hidden('preset_type');
        $form->text('keyword', '预置词')->required('不能为空');
        $form->userProfile('user_profile', '用户分群')->generate();

        $form->action('/admin/search/preset/recommend/save');
        return $content
            ->header($header)
            ->breadcrumb(
                ['text' => '搜索预置词推荐管理', 'url' => '/search/preset/recommend/' . $type],
                ['text' => $header, 'url' => '/search/preset/recommend/' . $type . '/create']
            )
            ->body($form->render());
    }

    public function del($step, $id)
    {
        $rs = mPresetSearchKeyword::updateData(['preset_status' => mPresetSearchKeyword::STATUS_DELETE], ['id' => $id]);
        if ($rs) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }
    }

    public function save(Request $request)
    {
        $request = $request->all();
        $id = (int)$request['id'];
        $keyword = $request['keyword'];
        $type = $request['preset_type'];

        $data = [
            'keyword' => $keyword,
            'preset_type' => $type,
        ];

        //分群信息
        $userProfile = $request['user_profile'];

        if ($id) {
            $rs = mPresetSearchKeyword::updateData($id, $data);
        } else {
            $rs = mPresetSearchKeyword::insertData($data);
        }

        if ($rs) {
            //更新用户分群
            $id = $request['id'] ? : $rs;
            AdmOperationModule::addUserProfile($id, $userProfile, PositionRules::MODULE_TYPE_SEARCH_KEYWORD);
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/search/preset/recommend/' . $type)->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            return redirect('/admin/search/preset/recommend/' . $type)->with(compact('error'));
        }


    }


}